const express = require('express');
const router = express.Router();
const Message = require("../model/messages")
const User = require("../model/users")
// 引入token
const jwt = require('jsonwebtoken');
const res = require('express/lib/response');

// 添加用户
router.post('/reg', async (req, res) => {
    const {
        username,
        password,
        phone
    } = req.body;
    if (!username) return res.send({
        success: false,
        info: '请输入正确的用户名'
    });
    if (!password) return res.send({
        success: false,
        info: '请输入正确的密码'
    });
    if (!/^1[3-9]\d{9}$/.test(phone)) return res.send({
        success: false,
        info: '请输入正确的手机号'
    });

    try {
        const users = await User.findOne({
            username
        });
        console.log(users);
        if (users) return res.send({
            success: false,
            info: '此用户名已被使用'
        });

        await User.create({
            username,
            password,
            phone,
        })

        res.send({
            success: true,
            info: '注册成功'
        })
    } catch (e) {
        res.send({
            success: false,
            info: '注册失败'
        })
    }
})

//用户登录
router.post('/login', async (req, res) => {
    const {
        username,
        password
    } = req.body;
    if (!username) return res.send({
        success: false,
        info: '请输入正确的用户名'
    });
    if (!password) return res.send({
        success: false,
        info: '请输入正确的用户名'
    });
    try {
        const user = await User.findOne({
            username,
            password
        });
        //判断用户名是否存在
        if (!user) return res.send({
            success: false,
            info: '用户错误'
        });
        if (!password) return res.send({
            success: false,
            info: '密码错误'
        });
        // // 生成一个token
        // const token = jwt.sign({
        //     uid: user._id,
        // }, '123456', {
        //     expiresIn: 60 * 60 * 1000
        // })
        res.send({
            success: true,
            info: '登录成功',
            // token,
            username
        });
    } catch (e) {
        console.log('e', e);
        res.send({
            success: false,
            info: '登陆失败'
        });
    }
})


// //text
// router.post('/test', (res, req) => {
//     const { token } = req.header;
//     res.send({
//         success: true,
//         token
//     })
// })


// 获取单个用户信息
router.get('/findOne', async (req, res) => {
    const one = await User.findOne({
        username
    })
    res.send(one.username)
})

// 添加信息
router.post('/addmessage', async (req, res) => {
    const {
        url,
        cover,
        title,
        author,
        type,
        msg
    } = req.body;
    console.log('req', req.body)
    // 数据过滤
    if (!title || !author || !type || !msg) return res.send({
        success: false,
        info: '请填写必要参数'
    });

    // 添加入库
    try {

        await Message.create({
            url,
            cover,
            title,
            author,
            type,
            msg
        })
        res.send({
            success: true,
            info: '添加成功'
        })

    } catch (e) {
        console.log(e)
        res.send({
            success: false,
            info: '未知错误 请于网站管理员联系'
        });
    }

})

//  查询全部信息
router.post('/getAllmessage', async (req, res) => {
    let {
        page,
        limit,
        title,
        type
    } = req.body;
    console.log('type', type);
    page = page || 1; // 当前第几页
    limit = limit || 20; // 单页返回的条数限制


    // 初始化 查询条件
    let where = {}
    // 按名字查找
    if (type) where.type = type;



    const skip = (page - 1) * limit; // 查询的起点（偏移量）
    try {
        let albums = await Message.find(where, {}, {
            skip,
            limit
        }) // 分页查询
        let count = await Message.count(where) // 获取符合条件的总数
        res.send({
            success: true,
            info: '查询成功',
            data: albums,
            count
        });
    } catch (e) {
        console.log(e)
        res.send({
            success: false,
            info: '获取失败'
        })
    }

})



//  获取单个信息
router.post('/mseeagedetail', async (req, res) => {

    const {
        _id
    } = req.body;
    if (!_id) return res.send({
        success: false,
        info: '请一定要传入id'
    })

    try {
        let message = await Message.findById(_id)
        console.log('mess', message)

        res.send({
            success: true,
            info: '查询成功',
            data: message
        });
    } catch (e) {

        res.send({
            success: false,
            info: '获取失败'
        })
    }

})


//搜索信息

router.post('/search', async (req, res) => {

    const {
        ask
    } = req.body;
    if (!ask) return res.send({
        success: false,
        info: '获取失败'
    })

    let where = {
        $or: [{
            "title": {
                "$regex": ask || !' '
            }
        }, {
            "author": {
                "$regex": ask || !' '
            }
        }, {
            "type": {
                "$regex": ask || !' '
            }
        }, {
            "author": {
                "$regex": ask || !' '
            }
        }]
    }

    try {
        const one = await Message.find(where)
        console.log(one)

        res.send({
            success: true,
            info: '查询成功',
            data: one
        });
    } catch (e) {

        res.send({
            success: false,
            info: '获取失败'
        })
    }

})





module.exports = router;